﻿if (!InfoSource) var InfoSource = {};
if (!InfoSource.ZipCodeLookup) InfoSource.ZipCodeLookup = {};

InfoSource.ZipCodeLookup.ZipCodePolygon = null;
InfoSource.ZipCodeLookup.Map = null;
InfoSource.ZipCodeLookup.InfoWindow = null;

InfoSource.ZipCodeLookup.Init = function () {
	InfoSource.ZipCodeLookup.Searchbox = $("#zipcode-searchbox");

	InfoSource.ZipCodeLookup.Searchbox
		.autocomplete({
			source: $.map(
				InfoSource.ZipCodeLookup.TypeAheadZipCodes
				, function (item, index) {
					return { value: index, label: index + " , " + item };
				}
			)
		});


	var mapOptions = {
		zoom: 8,
		center: new google.maps.LatLng(38.98, -105.55), /* just off center of colorado springs cuz thats the closest to centering the state in the viewport */
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		panControl: false,
		streetViewControl: false,
		scaleControl: false,
		zoomControl: false,
		mapTypeControl: false
	};

	InfoSource.ZipCodeLookup.Map = new google.maps.Map(document.getElementById("zipcode-lookup-zipcode-map"),
	mapOptions);

	InfoSource.ZipCodeLookup.ZipCodePolygon = new google.maps.Polygon(null);

}

/*========================================================================================*/
InfoSource.ZipCodeLookup.InitHandlers = function () {
	InfoSource.ZipCodeLookup.Searchbox.on("autocompleteselect",
		function (event, ui) {
			InfoSource.ZipCodeLookup.SelectZipcode(ui.item.value);
		});

	$(".work-performed-list").on("click", ".list-item",
		function () {
			var code = $(this).attr("contractor-code") || "";
			InfoSource.ZipCodeLookup.ToggleContractorDetailsPanel("open");
			InfoSource.ZipCodeLookup.LoadContractorDetailsIntoPanel(code);
		});

	$("#contractor-details-panel-handle").on("click",
		function () {
			InfoSource.ZipCodeLookup.ToggleContractorDetailsPanel();
		});
}

/*========================================================================================*/
InfoSource.ZipCodeLookup.ToggleContractorDetailsPanel = function (switchTo) {
	var $panel = $("#contractor-details-panel");
	switchTo = switchTo || ($panel.attr("status") == "closed" ? "open" : "closed");

	switch (switchTo) {
		case "open":
			$panel.css("left", "0px");
			$panel.attr("status", "open");
			break;

		case "closed":
			$panel.css("left", "-522px");
			$panel.attr("status", "closed");
			break;
	}
}

/*========================================================================================*/
InfoSource.ZipCodeLookup.LoadContractorDetailsIntoPanel = function (code) {
	var details = {};
	var $panel = $("#contractor-details-panel");
	var $content = $panel.find("#contractor-details-panel-content");
	$content
		.append($("<div class='loader'>")
					.css(
							{ "position": "absolute"
							, "top": "0px"
							, "left": "0px"
							, "width": "100%"
							, "height": "100%"
							, "background": "url('content/images/ajax-loader-large.gif') white"
							, "opacity": ".5"
							}
						)
		);
	InfoSource.ZipCodeLookup.ToggleContractorDetailsPanel("open");

	InfoSource.ZipCodeLookup.GetContractorDetails(code)
		.done(function (data) {
			var html = "";

			if (data) {
				var template = $("#zipcode-lookup-contractor-details-panel-template").html();
				html = template
					.replace(/\{name\}/gi, data.Name)
					.replace(/\{code\}/gi, data.Code)
					.replace(/\{phone\}/gi, data.Phone)
					.replace(/\{fax\}/gi, data.Fax)
					.replace(/\{restrictions\}/gi, data.Restrictions)
					.replace(/\{hvac service plan\}/gi, (data.DoesServicePlanHVAC ? "does" : "doesnt"))
					.replace(/\{hvac brokering\}/gi, (data.DoesBrokeringHVAC ? "does" : "doesnt"))
					.replace(/\{appliance service plan\}/gi, (data.DoesServicePlanAppliances ? "does" : "doesnt"))
					.replace(/\{appliance brokering\}/gi, (data.DoesBrokeringAppliances ? "does" : "doesnt"))
					.replace(/\{miscellaneous\}/gi, (data.DoesMiscellaneous ? "does" : "doesnt"))
			}
			else {
				html = "failed to load data for contractor";
			}
			$content.html(html);
			$content.find(".loader").remove();

		});

		/*
			<span class="contractor-name">{name}</span><span class="contractor-code">{code}</span>
	<table>
		<tr>
			<td class="label">Phone:</td>
			<td class="phone">{phone}</td>
		</tr>
		<tr>
			<td class="label">Fax:</td>
			<td class="fax">{fax}</td>
		</tr>
		<tr>
			<td class="label">Restrictions:</td>
			<td class="restrictions">{restrictions}</td>
		</tr>
		<tr>
			<td class="label">Work:</td>
			<td class="work">
				<div class="{hvac service plan}">HVAC Service Plan</div>
				<div class="{hvac brokering}">HVAC Brokering</div>
				<div class="{appliance service plan}">Appliance Service Plan</div>
				<div class="{appliance brokering}">Appliance Brokering</div>
				<div class="{miscellaneous}">Miscellaneous</div>
			</td>
		</tr>
	</table>
		*/
}

/*========================================================================================*/
InfoSource.ZipCodeLookup.GetContractorDetails = function(code){
	return $.getJSON("/infosource/api/GetContractorDetails?code=" + code);
}

/*========================================================================================*/
InfoSource.ZipCodeLookup.SelectZipcode = function (zipcode) {
	var zipcodeDetails = InfoSource.ZipCodeLookup.ZipCodeContractorDetails[zipcode];

	var spHVACElement = $("#zipcode-lookup-ServicePlanHVACContractors");
	var spHVACList = zipcodeDetails.ServicePlanHVACContractors || [];
	InfoSource.ZipCodeLookup.RenderList(spHVACElement, spHVACList);

	var spApplianceElement = $("#zipcode-lookup-ServicePlanApplianceContractors");
	var spApplianceList = zipcodeDetails.ServicePlanApplianceContractors || [];
	InfoSource.ZipCodeLookup.RenderList(spApplianceElement, spApplianceList);

	var brokeringHVACElement = $("#zipcode-lookup-BrokeringHVACContractors");
	var brokeringHVACList = zipcodeDetails.BrokeringHVACContractors || [];
	InfoSource.ZipCodeLookup.RenderList(brokeringHVACElement, brokeringHVACList);

	var brokeringApplianceElement = $("#zipcode-lookup-BrokeringApplianceContractors");
	var brokeringApplianceList = zipcodeDetails.BrokeringApplianceContractors || [];
	InfoSource.ZipCodeLookup.RenderList(brokeringApplianceElement, brokeringApplianceList);

	var miscellaneousElement = $("#zipcode-lookup-MiscellaneousContractors");
	var miscellaneousList = zipcodeDetails.MiscellaneousContractors || [];
	InfoSource.ZipCodeLookup.RenderList(miscellaneousElement, miscellaneousList);

	$("#zipcode-lookup-zipcode-data-field").text(zipcode);
	$("#zipcode-lookup-city-data-field").text(InfoSource.ZipCodeLookup.TypeAheadZipCodes[zipcode]);

	var firstPolygonCoordinates;
	InfoSource.ZipCodeLookup.RetrieveZipcodePolygonCoordinates(zipcode)
		.done(function (data) {
			if (data != null && data != undefined && data.length > 0) {
				firstPolygonCoordinates = data[0];
				InfoSource.ZipCodeLookup.RenderZipcodePolygon(firstPolygonCoordinates);

				InfoSource.ZipCodeLookup.RetrieveSeniorAndSpecialistForZipCode(zipcode)
					.done(function (data) {
						var firstPolygonCoordinatesPoint = firstPolygonCoordinates[0];
						var latLong = new google.maps.LatLng(firstPolygonCoordinatesPoint.Lat, firstPolygonCoordinatesPoint.Lng)

						InfoSource.ZipCodeLookup.RenderSeniorAndSpecialistInfoWindow(latLong, data);
					});
			}
		});


}

/*========================================================================================*/
InfoSource.ZipCodeLookup.RenderList = function ($list, items) {
	items = items || [];

	if (items.length == 0) {
		$list.html("<span class='none'>NONE</span>");
		return;
	}

	var html = ["<ul>"];
	var listItemTemplate = $("#zipcode-lookup-list-item-template").html();

	for (var x = 0; x < items.length; x++) {
		var currentItem = items[x];
		//<li class="list-item" contractor-code="{contractor code}">{contractor name}</li>
		var listItem = listItemTemplate
			.replace(/\{contractor code\}/gi, currentItem.Code)
			.replace(/\{contractor name\}/gi, currentItem.Name);

		html.push(new String(listItem));
	}

	html.push("</ul>");

	$list.html(html.join(""));

}

/*========================================================================================*/
InfoSource.ZipCodeLookup.RetrieveZipcodePolygonCoordinates = function (zipcode) {

	return $.getJSON("/infosource/api/GetCoordinatesFromKMLFile?zipcode=" + zipcode);
}

/*========================================================================================*/
InfoSource.ZipCodeLookup.RetrieveSeniorAndSpecialistForZipCode = function (zipcode) {

	return $.getJSON("/infosource/api/GetSeniorAndSpecialistForZipCode?zipcode=" + zipcode);
}

/*========================================================================================*/
InfoSource.ZipCodeLookup.RenderZipcodePolygon = function (coordinates) {
	InfoSource.ZipCodeLookup.ZipCodePolygon.setMap(null);
	if (InfoSource.ZipCodeLookup.InfoWindow) InfoSource.ZipCodeLookup.InfoWindow.close();

	var latLngs = [];
	for (var x = 0; x < coordinates.length; x++) {
		var curCoord = coordinates[x];

		latLngs.push(new google.maps.LatLng(curCoord.Lat, curCoord.Lng));
	}

	InfoSource.ZipCodeLookup.ZipCodePolygon = new google.maps.Polygon({
		paths: latLngs,
		strokeColor: "#FF0000",
		strokeOpacity: 0.8,
		strokeWeight: 2,
		fillColor: "#FF0000",
		fillOpacity: 0.35
	});

	InfoSource.ZipCodeLookup.ZipCodePolygon.setMap(InfoSource.ZipCodeLookup.Map);
	InfoSource.ZipCodeLookup.Map.setCenter(latLngs[0]);
	

	/*
	var a = InfoSource.GoogleMapLatlngToPoint(InfoSource.ZipCodeLookup.Map, latLngs[0]);

	$("body").append($("<div>hellow</div>").css(
		{
			position: "absolute",
			border: "2px solid black",
			background: "yellow",
			width: "50px",
			height: "50px",
			left: $(InfoSource.ZipCodeLookup.Map.getDiv()).position().left + a.x - 25,
			top: $(InfoSource.ZipCodeLookup.Map.getDiv()).position().top + a.y
		}
	));
	*/

}

/*========================================================================================*/
InfoSource.ZipCodeLookup.RenderSeniorAndSpecialistInfoWindow = function (latLng, data) {
	if (InfoSource.ZipCodeLookup.InfoWindow) InfoSource.ZipCodeLookup.InfoWindow.close();
	if (!data || (data.Senior.Code == null && data.Specialist.Code == null)) return;

	var template = $("#zipcode-lookup-senior-and-specialist-infowindow-template").html();

	var html = template
		.replace(/\{senior code\}/gi, data.Senior.Code)
		.replace(/\{senior image url\}/gi, "/infosource/content/images/hs-techs/temp.jpg") //" + data.Senior.Code + ".jpg")
		.replace(/\{senior name\}/gi, data.Senior.Name)
		.replace(/\{specialist code\}/gi, data.Specialist.Code)
		.replace(/\{specialist image url\}/gi, "/infosource/content/images/hs-techs/temp.jpg") //" + data.Specialist.Code + ".jpg")
		.replace(/\{specialist name\}/gi, data.Specialist.Name)

	$("#zipcode-lookup-senior-and-specialist-infowindow").html(html);

	/*
	InfoSource.ZipCodeLookup.InfoWindow = new google.maps.InfoWindow({
	content: template,
	position: latLng
	});

	InfoSource.ZipCodeLookup.InfoWindow.open(InfoSource.ZipCodeLookup.Map);
	*/
}

/*======================================================================================*/
$(document).ready(function () {
	InfoSource.ZipCodeLookup.Init();
	InfoSource.ZipCodeLookup.InitHandlers();
});